package com.food.chronicles.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.food.chronicles.dto.Ingredient;
import com.food.chronicles.dto.RecipeDetail;
import com.food.chronicles.dto.RecipeStep;
import com.food.chronicles.entity.primary.Recipe;
import com.food.chronicles.entity.secondary.Recipes;
import com.food.chronicles.mapper.primary.RecipeMapper;
import com.food.chronicles.mapper.secondary.RecipesMapper;
import com.food.chronicles.util.JsonUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class DataSyncService {

    Logger logger = org.slf4j.LoggerFactory.getLogger(DataSyncService.class);

    @Autowired
    private RecipesMapper recipesMapper;

    private static final int PAGE_SIZE = 100; // 每页处理100条记录，可根据实际情况调整

    @Autowired
    private RecipeMapper recipeMapper;

    @Autowired
    private IRecipeService recipeService;

    @Autowired
    private IRecipesService recipesService;

    /**
     * 同步xiachufang.recipes表到food.recipe表
     */
    public void syncRecipesData() {
        int pageNum = 1;
        boolean hasNextPage = true;

        while (hasNextPage) {
            try {
                // 分页查询未同步的数据
                IPage<Recipes> page = new Page<>(pageNum, PAGE_SIZE);
                LambdaQueryWrapper<Recipes> wrapper = Wrappers.lambdaQuery();
                wrapper.eq(Recipes::getSyncFlag, 0);
                wrapper.orderByAsc(Recipes::getId);

                IPage<Recipes> recipesPage = recipesMapper.selectPage(page, wrapper);
                List<Recipes> recipesToSync = recipesPage.getRecords();

                if (recipesToSync.isEmpty()) {
                    logger.info("没有需要同步的食谱数据");
                    break;
                }

                // 转换数据
                List<Recipe> recipesToSave = recipesToSync.stream()
                        .map(this::convertToRecipe)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());

                if (!recipesToSave.isEmpty()) {
                    // 直接调用Service的方法，确保事务生效
                    recipeService.saveBatchWithTransaction(recipesToSave);
                    recipesService.updateSyncStatusWithTransaction(recipesToSync);
                }

                hasNextPage = recipesPage.getCurrent() < recipesPage.getPages();
                pageNum++;

                logger.info("已同步第{}页，共{}条记录", pageNum - 1, recipesToSync.size());
            } catch (Exception e) {
                logger.error("同步第{}页数据失败", pageNum, e);
                break;
            }
        }
    }




    /**
     * 将Recipes实体转换为Recipe实体
     */
    private Recipe convertToRecipe(Recipes source) {
        if (source == null || source.getDetailJson() == null) {
            return null;
        }

        Recipe target = new Recipe();
        try {
            // 解析detailJson为详情对象
            RecipeDetail detail = (RecipeDetail)JsonUtil.json2object(source.getDetailJson(), RecipeDetail.class);

            // 基本字段映射
            target.setTitle(detail.getTitle());
            target.setCategory(mapCategory(source.getCategoryId()));
            target.setCoverImage(getFirstStepImage(detail.getSteps()));
            target.setDescription(generateDescription(detail.getSteps()));
            target.setIngredients(convertIngredientsToJson(detail.getIngredients()));
            target.setSteps(convertStepsToJson(detail.getSteps()));
            target.setDifficulty(2); // 默认为中等难度，可根据实际情况映射
            target.setPrepTime(10);  // 默认准备时间，可根据实际情况提取
            target.setCookTime(20);  // 默认烹饪时间，可根据实际情况提取
            target.setTotalTime(30); // 默认总时间，可根据实际情况计算
            target.setServes(2);     // 默认2人份，可根据实际情况提取

            // 设置其他字段
            target.setCreatorId(1L); // 默认创建者ID
            target.setLikeCount(detail.getVote_count() != null ? detail.getVote_count() : 0);
            target.setCollectCount(0);
            target.setCommentCount(0);
            target.setIsFeatured(0);

            Date date = new Date();
            // 设置时间
            target.setCreateTime(source.getCreateTime() != null ? source.getCreateTime() : date);
            target.setUpdateTime(date);

        } catch (Exception e) {
            logger.error("解析食谱详情JSON失败", e);
        }

        return target;
    }


    /**
     * 映射分类ID
     */
    private Integer mapCategory(String categoryId) {
        // 这里需要根据实际业务逻辑实现分类ID的映射
        // 示例: return Integer.parseInt(categoryId);
        return 1; // 默认分类ID，需根据实际情况修改
    }

    /**
     * 获取第一步的图片作为封面图
     */
    private String getFirstStepImage(List<RecipeStep> stepList) {
        if (stepList != null && !stepList.isEmpty()) {
            return stepList.get(0).getImage();
        }
        return "";
    }

    /**
     * 生成食谱描述
     */
    private String generateDescription(List<RecipeStep> stepList) {
        if (stepList != null && !stepList.isEmpty()) {
            return stepList.get(0).getDescription();
        }
        return "这是一道美味的食谱";
    }

    /**
     * 将食材列表转换为JSON字符串
     */
    private String convertIngredientsToJson(List<Ingredient> ingredientList) {
        try {
            return JsonUtil.toJson(ingredientList);
        } catch (Exception e) {
            logger.error("转换食材列表到JSON失败", e);
            return "[]";
        }
    }

    /**
     * 将步骤列表转换为JSON字符串
     */
    private String convertStepsToJson(List<RecipeStep> stepList) {
        try {
            return JsonUtil.toJson(stepList);
        } catch (Exception e) {
            logger.error("转换步骤列表到JSON失败", e);
            return "[]";
        }
    }
}